package com.ihealthway.all.groupbuy.modules.admin;

import com.ihealthway.all.groupbuy.services.SysAdminService;
import com.ihealthway.all.slog.annotation.SLog;
import com.ihealthway.all.commons.Constants;
import com.ihealthway.all.utils.Ajax;
import com.ihealthway.all.utils.AjaxReturn;
import com.ihealthway.all.groupbuy.vo.SysAdmin;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Encoding;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.lang.Times;
import org.nutz.lang.hardware.Networks;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.NutConfig;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Date;
import java.util.Properties;

/**
 * Background index module class
 *
 * @author 凡梦星尘(elkan1788@gmail.com)
 */
@At("/admin")
@IocBean
public class IndexModule {

    private static final Log logger = Logs.get();

    @Inject
    private SysAdminService sysAdminService;

    @At("/login")
    @Ok("beetl:admin/login.jsp")
    public void login() {

    }

    @POST
    @At
    public AjaxReturn checkLogin(@Param("..")SysAdmin sysAdmin, HttpServletRequest req) {

        AjaxReturn ar = Ajax.ok();

        String loginAct = sysAdmin.getAccount();
        String loginPswd = sysAdmin.getPasswd();

        if (sysAdmin==null
                || loginAct==null
                || loginAct.isEmpty()
                || loginPswd==null
                || loginPswd.isEmpty()) {
            ar.setOk(false);
            ar.setErrCode("401");
            ar.setMsg("请输入用户与密码登录.");
            return ar;
        }

        logger.infof("Login admin object: %s", sysAdmin.toString());

        sysAdmin = sysAdminService.checkLogin(loginAct);
        if (sysAdmin==null || !sysAdmin.validPasswd(loginPswd)) {
            ar.setOk(false);
            ar.setErrCode("401");
            ar.setMsg("请输入用户与密码登录.");
            return ar;
        }


        logger.infof("Login success admin object: %s", sysAdmin.toString());

        req.getSession().setAttribute(Constants.ADMIN_LOGIN_SESSION, sysAdmin);

        SysAdmin updateSysAdmin = (SysAdmin) sysAdmin.clone();
        if (updateSysAdmin!=null) {
            updateSysAdmin.setLoginCnt(updateSysAdmin.getLoginCnt()+1);
            updateSysAdmin.setUpdateTime(new Date());
            sysAdmin.setIpAddr(Lang.getIP(req));

            sysAdminService.update(updateSysAdmin);
        }

        ar.setMsg("登录成功.");
        ar.setData("/admin/index.do");

        return ar;
    }

    @At("/index")
    @Ok("beetl:admin/index.jsp")
    public void index(HttpServletRequest req) {
        HttpSession session = req.getSession();
        SysAdmin sysAdmin = (SysAdmin) session.getAttribute(Constants.ADMIN_LOGIN_SESSION);
        req.setAttribute("admin", sysAdmin);
    }

    @POST
    @At
    @SLog(module = Constants.MODULE_SYSTEM, type = Constants.OPERATE_TYPE_UPDATE, content = "更新管理员【${args[0].nickName}】个人信息")
    public AjaxReturn updateAdminInfo(@Param("..") SysAdmin sysAdmin) {
       AjaxReturn ar = Ajax.ok();

       if (sysAdmin.getPasswd()==null ||sysAdmin.getPasswd().isEmpty()) {
           sysAdmin.setPasswd(null);
       } else {
           sysAdmin.setPasswd(Lang.md5(sysAdmin.getPasswd()));
       }

       ar.setOk(sysAdminService.update(sysAdmin));
       if (!ar.isOk()) {
           ar.setErrCode("-1");
           ar.setMsg("更新管理员个人信息失败!");
       }

       return ar;
    }

    @At
    @Ok(">>:/admin/login.do")
    public void logout(HttpServletRequest req) {
        HttpSession session = req.getSession();
        session.removeAttribute(Constants.ADMIN_LOGIN_SESSION);
    }

    @At("/default")
    @Ok("beetl:admin/default.jsp")
    public void defPage(HttpServletRequest req) {

        HttpSession session = req.getSession();
        SysAdmin sysAdmin = (SysAdmin) session.getAttribute(Constants.ADMIN_LOGIN_SESSION);

        Properties serverInfo = new Properties();
        serverInfo.putAll(System.getProperties());

        String encoding = Encoding.defaultEncoding();
        String curPath = new File(".").getAbsolutePath();
        String jdkVersion = serverInfo.getProperty("java.version", Constants.SYS_ERROR);
        String fileSep = serverInfo.getProperty("file.separator", Constants.SYS_ERROR);
        String timezone = serverInfo.getProperty("user.timezone", Constants.SYS_ERROR);
        String OSName = serverInfo.getProperty("os.name",Constants.SYS_ERROR)
                + "," + serverInfo.getProperty("os.arch", Constants.SYS_ERROR);

        NutConfig config = Mvcs.getNutConfig();
        String servletInfo = config.getServletContext().getServerInfo();
        String servletVer = Integer.valueOf(config.getServletContext().getMajorVersion()) + "."
                + Integer.valueOf(config.getServletContext().getMinorVersion());
        String servletEnter = "/";
        if (config.getServletContext().getMajorVersion() > 2
                || config.getServletContext().getMinorVersion() > 4) {
            servletEnter = config.getServletContext().getContextPath();
            servletEnter = (servletEnter == null || servletEnter.isEmpty()) ? "/" : servletEnter;
        }

        String mac = Constants.SYS_ERROR;
        String ip = Constants.SYS_ERROR;
        try {
            mac = Networks.mac();
            ip = Networks.ipv4();
        } catch (Exception e) {
            logger.error("Get networks information failed", e);
        }

        serverInfo.clear();

        serverInfo.put("default.encoding", encoding);
        serverInfo.put("current.path", curPath);
        serverInfo.put("jdk.version", jdkVersion);
        serverInfo.put("file.separator", fileSep);
        serverInfo.put("user.timezone", timezone);
        serverInfo.put("machine.mac", mac);
        serverInfo.put("network.address", ip);
        serverInfo.put("operate.system", OSName);
        serverInfo.put("servlet.info", servletInfo);
        serverInfo.put("servlet.version", servletVer);
        serverInfo.put("servlet.enter", servletEnter);

        serverInfo.put("login.lastTime", Times.format("yyyy-MM-dd HH:mm:ss", sysAdmin.getUpdateTime()));
        serverInfo.put("login.ipAddr", sysAdmin.getIpAddr());

        req.setAttribute("serverInfo", serverInfo);
    }

    @At("/monitor")
    @Ok("beetl:admin/monitor.jsp")
    public void monitor(@Param("mt") String monitorType, HttpServletRequest req) {
        if (Strings.equals("druid", monitorType)) {
            req.setAttribute(Constants.FORWARD_PATH, "/druid/index.html");
        } else {
            req.setAttribute(Constants.FORWARD_PATH, "/admin/monitoring.action");
        }
    }

    @At
    @Ok("beetl:admin/dashboard.jsp")
    public void dashboard() {

    }
}
